package com.hj.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hj.system.config.security.base.UserInfo;
import com.hj.system.entity.base.*;
import com.hj.system.mapper.*;
import com.hj.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wxf
 * @since 2021-04-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public UserEntity queryUserPermissions() {
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userId = userInfo.getUserId();
        UserEntity userEntity = baseMapper.selectById(userId);
        List<UserRoleEntity> userRoleEntities = userRoleMapper.selectList(new QueryWrapper<UserRoleEntity>() {
        }.eq("user_id", userId));
        List<Integer> roleIds = userRoleEntities.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList());
        List<RoleEntity> roleEntities = roleMapper.selectList(new QueryWrapper<RoleEntity>() {
        }.in("role_id", roleIds));
        List<RoleMenuEntity> roleMenuEntities = roleMenuMapper.selectList(new QueryWrapper<RoleMenuEntity>() {
        }.in("role_id", roleIds));
        List<Integer> menuIds = roleMenuEntities.stream().map(RoleMenuEntity::getMenuId).collect(Collectors.toList());
        List<MenuEntity> menuEntities = menuMapper.selectList(new QueryWrapper<MenuEntity>() {
        }.in("menu_id", menuIds));
        userEntity.setRoles(roleEntities);
        userEntity.setMenus(menuEntities);
        userEntity.setPassword(null);
        return userEntity;
    }
}
